'use client';

import { MoonIcon, SunIcon } from '@heroicons/react/24/outline';
import clsx from 'clsx';
import { useAtom } from 'jotai';
import { memo, useEffect, useState } from 'react';
import { appThemeAtom } from 'src/model';

export interface ThemeControllerProps {
  className?: string;
  /**
   * 监听器
   * @description 监听器模式，只用于监听主题，不渲染任何内容
   */
  isListener?: boolean;
}

function ThemeControllerNoMemoized(props: ThemeControllerProps) {
  const { className, isListener } = props;

  const [theme, setTheme] = useAtom(appThemeAtom);
  const [initialTheme] = useState(theme);

  useEffect(() => {
    if (isListener) {
      const root = document.documentElement;
      root.setAttribute('data-theme', theme);
    }
  }, [isListener, theme]);

  if (isListener) {
    return null;
  }

  return (
    <label
      title="切换主题"
      className={clsx(
        'swap swap-rotate p-2 rounded-full hover:bg-gray-200 dark:hover:bg-neutral-700 transition-colors',
        className
      )}
    >
      {/* this hidden checkbox controls the state */}
      <input
        type="checkbox"
        className="theme-controller"
        value={theme}
        onChange={() => {
          setTheme((prev) => (prev === 'light' ? 'dark' : 'light'));
        }}
      />

      {/* sun icon */}
      <SunIcon className={clsx('size-6', initialTheme === 'dark' ? 'swap-on' : 'swap-off')} />

      {/* moon icon */}
      <MoonIcon className={clsx('size-6', initialTheme === 'dark' ? 'swap-off' : 'swap-on')} />
    </label>
  );
}

export const ThemeController = memo(ThemeControllerNoMemoized);
